import 'dart:convert';
import 'dart:core';
import 'dart:io';
import 'package:flutter_inapp_purchase/flutter_inapp_purchase.dart';
import 'package:lcapp/api/interface/user_api.dart';
import 'package:lcapp/api/request/response_data.dart';
import 'package:lcapp/basic/user_info.dart';
import 'package:lcapp/model/db/apple_pay_operate.dart';
import 'package:lcapp/model/event/event_bus.dart';
import 'package:lcapp/model/share/custom_share.dart';
import 'package:lcapp/model/toast/toast.dart';
import 'package:tobias/tobias.dart';

/// 支付方式
enum PayType {
  /// 成长豆
  PayType_CZD,

  /// 微信支付
  PayType_WECHAT,

  /// 支付宝支付
  PayType_ALI,

  /// 苹果支付
  PayType_APPLE,

  /// 未知
  Un_Know,
}

/// 订单类型
class OrderType {
  /// 资源课
  static int VIPOrder = 1;
}

class InAppPay {
  static pay(
    PayType type,
    {
    int? orderId,
    double? money,
    double? total,
    String? sku,
    String? payInfo,
  }) {
    switch (type) {
      case PayType.PayType_CZD: //成长豆 参数  double money,double total
        czdPay(money!, total!);
        break;
      case PayType.PayType_ALI: //阿里支付 参数  aliPayInfo
        alibabaPay(payInfo!);
        break;
      case PayType.PayType_WECHAT: //微信支付 参数  weChatPayInfo
        weChatPay(payInfo!);
        break;
      case PayType.PayType_APPLE: //苹果支付 参数  String sku,String orderId
        applePay(sku!, orderId!);
        break;
      case PayType.Un_Know:
        // TODO: Handle this case.
        throw UnimplementedError();
    }
  }

  //成长豆支付
  static czdPay(double money, double total) async {
    userInfo.vip = 1;
    eventBus.fire(PayState(0, PayType.PayType_CZD));
  }

  //苹果支付
  static applePay(String sku, int orderId) async {
    showLoading();
    await FlutterInappPurchase.instance.getProducts([sku]);
    await FlutterInappPurchase.instance
        .requestPurchase(sku, obfuscatedAccountId: '$orderId');
  }

  //阿里支付
  static alibabaPay(String payInfo) async {
    if (payInfo == null) {
      return;
    }
    Tobias tobias = Tobias();
    tobias.pay(payInfo,evn: AliPayEvn.online).then((value) {
      if (value != null && int.parse(value['resultStatus']) == 9000) {
        userInfo.vip = 1;
        eventBus.fire(PayState(0, PayType.PayType_ALI)); //发送支付结果
      } else {
        eventBus.fire(PayState(-1, PayType.PayType_ALI)); //发送支付结果
      }
    });
  }

  //微信支付
  static weChatPay(String payInfo) async {
    if (payInfo == null) {
      return;
    }
    Map<String, dynamic> map = json.decode(payInfo);
    // CustomShare().WXPay(
    //   partnerId: map['partnerId'],
    //   prepayId: map['prepayId'],
    //   package: map['packageVal'], //'Sign=WXPay',
    //   nonceStr: map['nonceStr'],
    //   timeStamp: map['timestamp'],
    //   sign: map['sign'],
    // );
  }

  static initApplePay() async {
    if (Platform.isIOS) {
      var result = await FlutterInappPurchase.instance.initialize();
      print('result: $result');
      FlutterInappPurchase.instance.clearTransactionIOS();
      FlutterInappPurchase.purchaseUpdated.listen((productItem) async {
        print('purchase-updated: $productItem');
        hideLoading();
        Map<String, dynamic> map = {
          'productId': productItem?.productId,
        };
        Map order = await ApplePayDBOperate.getOrderInfo(map);
        checkApplePay(productItem!, order['orderId']);
      });
      FlutterInappPurchase.purchaseError.listen((purchaseError)async {
        print('purchase-error: $purchaseError');
        hideLoading();
        showToast('取消支付');
        eventBus.fire(PayState(-1, PayType.PayType_APPLE)); //发送支付成功的消息
      });
    }
  }

  static checkApplePay(PurchasedItem productItem, int orderId) async {
    showLoading();
    ResponseData res = await UserAPI.applePayCheck({
        'orderId':orderId,
        'transactionId':productItem.transactionId,
        'receipt':productItem.transactionReceipt
    });
    hideLoading();
    if (res.code == 200) {
      FlutterInappPurchase.instance.finishTransaction(productItem);
      ApplePayDBOperate.deletePayHistory(orderId);
      userInfo.vip = 1;
      eventBus.fire(PayState(0, PayType.PayType_APPLE)); //发送支付成功的消息
    } else {
      //凭证验证失败
      FlutterInappPurchase.instance.finishTransaction(productItem);
    }
  }

}
